use async_trait::async_trait;
use clap::Parser;
use tauri::api::shell::open;
use tauri::Manager;

use crate::commands::commands::Command;
use crate::models::models::command::CommandState;
use crate::state;
use crate::utils::command;

#[derive(Debug, Default, Clone, Parser)]
#[clap(disable_help_flag = true)]
struct Args {
    // 百度搜索引擎
    #[arg(long = "google", default_value_t = false)]
    google: bool,
    // 百度搜索引擎
    #[arg(long = "baidu", default_value_t = false)]
    baidu: bool,
    // 必应搜索引擎
    #[arg(long = "bing", default_value_t = false)]
    bing: bool,
    // 关键词
    value: Vec<String>,
}

#[derive(Debug, Clone, Default)]
pub(crate) struct SearchCommand {}

#[async_trait]
impl Command for SearchCommand {
    async fn execute(&self, command: crate::models::models::command::Command) -> crate::models::models::command::Command {
        let args = command::parse_command_args::<Args>(command.args.as_str());
        if args.is_err() {
            return self.save_command_output(command, CommandState::Failed, args.unwrap_err().to_string());
        }

        let args = args.unwrap();

        // 默认使用谷歌搜索
        let mut search_link = format!("https://www.google.com/search?q={}", args.value.join(" "));

        if args.baidu {
            search_link = format!("https://www.baidu.com/s?wd={}", args.value.join(" "));
        } else if args.bing {
            search_link = format!("https://www.bing.com/search?q={}", args.value.join(" "));
        } else if args.google {
            search_link = format!("https://www.google.com/search?q={}", args.value.join(" "));
        }

        let scope = state::application::app().shell_scope();
        let result = open(&scope, search_link.as_str(), None);
        if result.is_err() {
            return self.save_command_output(command, CommandState::Failed, result.err().unwrap().to_string());
        }

        self.save_command_output(command, CommandState::Success, search_link)
    }
}